package com.laikan.reader.bookstore.base;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.*;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.article.activity.BookFocusDetailActivity;
import com.laikan.reader.article.activity.FocusCommentActivity;
import com.laikan.reader.article.activity.FocusCommentDetailActivity;
import com.laikan.reader.bookfriend.mactivity.AutherActivity;
import com.laikan.reader.bookreader.activity.BookDesActivity;
import com.laikan.reader.bookstart.activity.HomeActivity;
import com.laikan.reader.bookstore.activity.BookSearchActivity;
import com.laikan.reader.bookstore.activity.BookStoreCalssifyActivity;
import com.laikan.reader.bookstore.activity.RankCategoryActivity;
import com.laikan.reader.bookstore.activity.RankingActivity;
import com.laikan.reader.bookstore.view.ScrollWebView;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.CustomSwipeRefreshLayout;
import com.laikan.reader.core.view.TipInfoLayout;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2016/10/20.
 */
public abstract class BasicWebViewActivity extends BasicActivity {
    private static final String TAG = "BasicWebViewActivity";
    protected static final String APP_CACAHE_DIRNAME = "/webcache";
    private String mHtmlUrl;
    protected ScrollWebView basicview_webview;
    protected CustomSwipeRefreshLayout basicview_swiperefresh;
    protected RelativeLayout webview_basic_root;
    protected TextView tv_title;
    protected ImageView iv_back, iv_search;
    protected boolean mIsPageLoadingSucess; //WebView页面是否加载成功
    protected BitmapDrawable drawable_back;
    protected boolean mIsRefreshWebBiew;//判断是否WebView是否刷新，如果刷新通过 basicview_swiperefresh  loading
    protected TipInfoLayout tipinfo;
    private String token, userId;

    @Override
    protected void assignViews() {
        setContentView(R.layout.activity_webview_basic);
        webview_basic_root = (RelativeLayout)findViewById(R.id.basicview_root);
        basicview_webview = (ScrollWebView)findViewById(R.id.basicview_webview);
        iv_back = (ImageView)findViewById(R.id.iv__back);
        iv_search = (ImageView)findViewById(R.id.iv_search);
        tv_title = (TextView)findViewById(R.id.tv_title);
        basicview_swiperefresh = (CustomSwipeRefreshLayout)findViewById(R.id.bookfocus_swiperefresh);
        basicview_swiperefresh.setColorSchemeResources(R.color.C_66ccdd);
        tipinfo = (TipInfoLayout)findViewById(R.id.tipinfo);

    }

    @Override
    protected void initData() {
        drawable_back = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        iv_back.setImageDrawable(drawable_back);
        initMainWebView();
        token = "sd=" + SPUtil.getString("token", "");
        userId = "userId=" + SPUtil.getString("user_id", "0");
    }

    /**
     * 页面跳转传值
     * @param titleContext
     * @param loadUrl
     */
    protected void setPageLoadData(String titleContext,String loadUrl)
    {
        tv_title.setText(titleContext);
        this.mHtmlUrl = loadUrl;
        requestData(true,null);
    }

    /**
     * 获取资源文件设置
     * @param titleContext
     * @param loadUrl
     */
    protected void setPageLoadData(int titleContext,String loadUrl)
    {
        tv_title.setText(titleContext);
        this.mHtmlUrl = loadUrl;
        requestData(true,null);

    }

    /**
     * load webview
     * @param isload TODO 拓展
     *
     */
    private void requestData(boolean isload,Map<String,String> param) {
        basicview_webview.postUrl(mHtmlUrl, token.getBytes());
    }

    /**
     * 迭代参数
     *
     * @param param
     */
    private String spliceParam(Map<String, String> param) {
        StringBuffer paramUp = new StringBuffer();
        Iterator entries = param.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry)entries.next();
            String key = (String)entry.getKey();
            String value = (String)entry.getValue();
            paramUp.append(key+"="+value);
        }

        return paramUp.toString();
    }

    @Override
    protected void setListener() {
        tipinfo.setOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isFinish = false;
                requestData(true,null);
            }
        });
        basicview_webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        iv_back.setOnClickListener(this);
        iv_search.setOnClickListener(this);
    }

    @Override
    protected void onClickEvent(View view) {
        super.onClickEvent(view);
        switch (view.getId()) {
            case R.id.iv__back:
                finish();
                break;
            case R.id.iv_search:
                Intent intent = new Intent();
                intent.setClass(mContext, BookSearchActivity.class);
                mContext.startActivity(intent);
                break;
            default:
                break;
        }
    }


    /**
     * init webview setting
     */
    protected void initMainWebView() {
        WebSettings webSetting = basicview_webview.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);//允许js弹出窗
        basicview_webview.addJavascriptInterface(new CallJavaInterface(), "android");// 通过调这个注册
        webSetting.setAllowFileAccess(true);
        // 判断是否使用硬件加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            basicview_webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        basicview_webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        basicview_webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        basicview_webview.getSettings().setDomStorageEnabled(true);
        // 开启 database storage API 功能
        basicview_webview.getSettings().setDatabaseEnabled(true);
        // TODO: 2016/10/20  接口有待改
        String cacheDirPath = this.getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME + mHtmlUrl;
        // 设置数据库缓存路径
        basicview_webview.getSettings().setDatabasePath(cacheDirPath);
        // 设置 Application Caches 缓存目录
        basicview_webview.getSettings().setAppCachePath(cacheDirPath);
        // 开启 Applicat ion Caches 功能
        basicview_webview.getSettings().setAppCacheEnabled(true);
        basicview_webview.getSettings().setAppCacheMaxSize(100);
        // 设置图片加载模式
        basicview_webview.getSettings().setBlockNetworkImage(false);
        // basicview_webview.getSettings().setBuiltInZoomControls(true);
        basicview_webview.getSettings().setUseWideViewPort(false);
        // 设置监听
        basicview_webview.getSettings().setLoadsImagesAutomatically(true);
        basicview_webview.setWebViewClient(webViewClient);
        basicview_swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                mIsRefreshWebBiew = true;
                //开始请求
                requestData(false,null);
            }
        });
    }

    protected boolean isFinish = false;
    /**
     * webviewClient
     */
    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mIsPageLoadingSucess = true;
            if (!mIsRefreshWebBiew) { tipinfo.setLoading(); }
        }

        // 接口错误404时 回调
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            if(!isFinish){
                view.loadUrl("");
                mIsPageLoadingSucess = false;
                tipinfo.setLoadErrorNotDelayed(R.string.laikan_network_anomaly);
                mIsRefreshWebBiew = false;

            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//            super.onReceivedError(view, errorCode, description, failingUrl);
            view.loadUrl("");
            mIsPageLoadingSucess = false;
            if (mIsPageLoadingSucess) {
                tipinfo.setHide();
            }else {
                tipinfo.setLoadErrorNotDelayed(R.string.laikan_network_anomaly);
                mIsRefreshWebBiew = false;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            basicview_swiperefresh.setRefreshing(false);
            dismissDialog();
//            mIsPageLoadingSucess = false;
            if (mIsPageLoadingSucess) {
                tipinfo.setHide();
            }else {
                tipinfo.setLoadErrorNotDelayed(R.string.laikan_network_anomaly);
                mIsRefreshWebBiew = false;
            }

            isFinish = true;
        }
    };

    /**
     * js and webview interact
     */
    private class CallJavaInterface {

        /**
         * 事件冲突
         */
        @JavascriptInterface
        public boolean ignoreTouchCancel(boolean flag) {
            if(flag){
                basicview_swiperefresh.setRefreshing(false);
            }
            return true;
        }

        /**
         * 书籍详情页
         */
        @JavascriptInterface
        public void callBook(String censusType,String bookId) {
            KLog.v(TAG, "call Book consusType : " + censusType + "  bookId :" + bookId);
            MobclickAgent.onEvent(mContext,censusType);
            Intent intent = new Intent(mContext, BookDesActivity.class);
            intent.putExtra("bookId", bookId);
            intent.putExtra("censusType", censusType);
            mContext.startActivity(intent);
        }

        /**
         * 作品列表  其中isShowOrder 标示是否显示列表序列号， 默认false
         */
        @JavascriptInterface
        public void callBookList(String censusType,String title, String rankUrl, boolean isShowOrder) {
            MobclickAgent.onEvent(mContext,censusType);
            KLog.v(TAG, "callBookList : title: " + title +"  rankUrl: " + rankUrl + "  isShowOrder : " + isShowOrder+"------------"+censusType);
            Intent intent = new Intent(mContext, RankCategoryActivity.class); //书籍排行列表
            intent.putExtra("title", title);
            intent.putExtra("rankUrl", rankUrl);
            intent.putExtra("isShowOrder", isShowOrder);
            intent.setAction("from_more_data");
            mContext.startActivity(intent);
        }

        /**
         *  关键字搜索
         */
        @JavascriptInterface
        public void callSearch(String censusType,String keyword) {
            KLog.v(TAG, "callSearch : censusType : " + censusType + " keyword : " + keyword);
            MobclickAgent.onEvent(mContext,censusType);
            SPUtil.putBoolean("isKeywordSearch", true);
            Intent intent = new Intent(mContext, BookSearchActivity.class);
            intent.putExtra("keyword", keyword);
            mContext.startActivity(intent);
        }

        /**
         * 排行榜首页
         */
        @JavascriptInterface
        public void callRank(String censusType) {
            KLog.v(TAG, "consusType :" + censusType);
            MobclickAgent.onEvent(mContext,censusType);
            Intent intent = new Intent(mContext, RankingActivity.class);
            mContext.startActivity(intent);
        }

        /**
         * 功能 HTML  其中isShowSearch 定义是否显示搜素等按钮，默认 false
         */
        @JavascriptInterface
        public void callHtml(String censusType,String title, String htmlUrl, boolean isShowSearch) {
            MobclickAgent.onEvent(mContext,censusType);
            KLog.v(TAG, "callHtml : title: " + title +"  htmlUrl: " + htmlUrl + "  isShowSearch : " + isShowSearch + " censusType : " + censusType);
                Intent intent = new Intent(mContext, BookStoreCalssifyActivity.class);
                intent.putExtra("title", title);
                intent.putExtra("htmlUrl", htmlUrl);
                intent.putExtra("isShowSearch", isShowSearch);
                mContext.startActivity(intent);
        }

        /**
         * 进入看文章详情
         */
        @JavascriptInterface
        public void callArticle(String censusType,String articleId){
            KLog.v(TAG, "callArticle : censusType : " + censusType + "  articleId : " + articleId);
            MobclickAgent.onEvent(mContext,censusType);
            Intent intent = new Intent(mContext, BookFocusDetailActivity.class);
            intent.putExtra("articleId", articleId);
            mContext.startActivity(intent);
        }

        /**
         * 客户端接口：看点文章评论列表
         */
        @JavascriptInterface
        public void callArticleReviewList(String articleId){
            KLog.v(TAG, "callArticleReviewList :  articleId : " + articleId);
            Intent intent = new Intent(mContext, FocusCommentActivity.class);
            intent.putExtra("shorteId", articleId);
            mContext.startActivity(intent);
        }

        /**
         * 文章回复
         */
        @JavascriptInterface
        public void callArticleReply(String articleId, String reviewId){
            KLog.v(TAG, "callArticleReply : articleId :" + articleId +"  reviewId: " + reviewId);
            Intent intent = new Intent(mContext, FocusCommentDetailActivity.class);
            intent.putExtra("shorteId", articleId);  //文章id
            intent.putExtra("replyId", reviewId);   // 评论id
            mContext.startActivity(intent);
        }
        /**
         * 跳转看点首页
         */
        @JavascriptInterface
        public void callKdIndex(){
            KLog.v(TAG,  "callKdIndex ");
            Intent intent = new Intent(mContext, HomeActivity.class);
            mContext.startActivity(intent);
        }

        /**
         * 跳转个人主页
         */
        @JavascriptInterface
        public void callAuthor(String authorId){
            KLog.v(TAG,  "callAuthor : authorId : " + authorId);
//            ToastMgr.showLongToast("author ID :" + authorId);
//            Intent intent = new Intent(mContext, HomeActivity.class);
//            mContext.startActivity(intent);
//            httpPost(authorId);
            Intent intent = new Intent(mContext,AutherActivity.class);
            intent.putExtra("userId",authorId);
//                    intent.putExtra("type","me");//标记intent的来源为我的页面
            startActivity(intent);
        }


        private void httpPost (String authorId){
            RequestListener requestListener = new RequestListener() {
                @Override
                public void onPreExecute() {

                }

                @Override
                public void onSuccess(HttpResponse httpResponse) {
                    KLog.json(httpResponse.responseContent);
                }

                @Override
                public void onError(VolleyErrorHandler errorHandler) {

                }

                @Override
                public void onFinish() {

                }
            };
            Requester requester = new Requester();
            requester.setUrl("http://api.motie.com/android/3/kandian/home");
            Map map = new <String, Object>HashMap();
            map.put("sd", SPUtil.getString("token", ""));
            map.put("authorId", authorId);
            requester.setMapBody(map);
            HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
        }
    }
}
